﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using NotepadDemo.Models;

namespace NotepadDemo.Helps
{

    public static class MyExtensionMethods
    {
        public static DataModel GetData(string fileNameOrSql)
        {
            string content = GetContent(fileNameOrSql);
            return JsonWrapper.Decode<DataModel>(content);
        }


        public static string GetContent(string fileName)
        {

            if (!File.Exists(fileName))
            {
                DataModel model = new DataModel();
                model.Uri = fileName;
                model.Content = "";
                model.Password = "";
                model.IsLocked = false;
                string content = JsonWrapper.Encode(model);
                FileSave(fileName, content);
            }

            try
            {
                using (FileStream fsSource = new FileStream(fileName,
                    FileMode.Open, FileAccess.Read, FileShare.Write))
                {

                    using (StreamReader reader = new StreamReader(fsSource, Encoding.UTF8))
                    {
                        string sr = reader.ReadToEnd();
                        return sr;
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                throw new Exception(e.ToString());
            }
        }

        public static bool FileSave(string fileName, string content)
        {
            if (!File.Exists(fileName))
                File.Create(fileName).Dispose();
            try
            {
                byte[] data = Encoding.UTF8.GetBytes(content);
                FileStream stream = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

                stream.Write(data, 0, data.Length);

                stream.Dispose();
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }

            return true;
        }
    }

}




